﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BSCMFF.Core.DataAccessLayer;
using Telerik.Web.UI;
using BSCMFF.Core.BusinessLayer;
using BSCMFF.Web.UserControls.Details;
using System.Collections;

namespace BSCMFF.Web.Pages
{
    public partial class BSCTreeList : System.Web.UI.Page
    {
        protected void Page_Init(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                RadCalendar1.SelectedDate = DateTime.Today;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //RadTreeList1.ExpandedIndexes.Add(new TreeListHierarchyIndex { LevelIndex = 0, NestedLevel = 0 });
                //RadTreeList1.ExpandedIndexes.Add(new TreeListHierarchyIndex { LevelIndex = 1, NestedLevel = 0 });
                //RadTreeList1.ExpandedIndexes.Add(new TreeListHierarchyIndex { LevelIndex = 2, NestedLevel = 0 });
                RadTreeList1.ExpandAllItems();

                TreeListDataItem item = RadTreeList1.Items[0];
                item.Selected = true;

            }
        }

        private List<BSCTreeListItem> bscdata;
        protected void RadTreeList1_NeedDataSource(object sender, TreeListNeedDataSourceEventArgs e)
        {
            //RadTreeList1.DataSource = MyData.GetData();
            //RadTreeList1.DataSource = BSCTreeListManager.GetData();
            //RadTreeList1.DataSource = BSCTreeListManager.GetDataByDate(DateTime.Today.AddDays(-1));
            //if (RadCalendar1.SelectedDate == null)
            //{
            //    RadTreeList1.DataSource = BSCTreeListManager.GetDataByDate(DateTime.Today);
            //}
            //else
            //{
            bscdata = BSCTreeListManager.GetDataByDate(RadCalendar1.SelectedDate);
            RadTreeList1.DataSource = bscdata;
            //}
        }

        protected void RadTreeList1_ItemDataBound(object sender, TreeListItemDataBoundEventArgs e)
        {
            if (e.Item is TreeListDataItem)
            {
                TreeListDataItem item = e.Item as TreeListDataItem;
                if (item.HierarchyIndex.NestedLevel == 1)
                {
                    (item.FindControl("img") as Image).ImageUrl = "~/Images/Root.GIF";
                    
                    item.BackColor = System.Drawing.ColorTranslator.FromHtml("#B5D6FD");

                }
                if (item.HierarchyIndex.NestedLevel == 2)
                {
                    //(item.FindControl("img") as Image).ImageUrl = "~/Images/Root.GIF";
                    item.BackColor = System.Drawing.ColorTranslator.FromHtml("#D7F5FF");

                }
                //long value = (long)DataBinder.Eval(item.DataItem, "Population");
                //item["Name"].BackColor = System.Drawing.Color.White;
            }
        }

        protected void RadCalendar1_SelectionChanged(object sender, Telerik.Web.UI.Calendar.SelectedDatesEventArgs e)
        {
            RadTreeList1_NeedDataSource(sender, new TreeListNeedDataSourceEventArgs(TreeListRebindReason.PostBackEvent));

        }

        protected void RadTreeList1_ItemCommand(object sender, TreeListCommandEventArgs e)
        {
            if (e.CommandName == RadTreeList.SelectCommandName)
            {                
                //BSCTreeListItem bli = bscdata[
                TreeListDataItem editedItem = (e.Item as TreeListDataItem);

                switch (editedItem["ItemType"].Text)
                {
                    case "KPI": ShowKPI(editedItem); break;
                    case "Perspective": ShowPerspective(editedItem); break;
                    default: ShowBSC(); break;
                }

                //(DKPI.FindControl("TextBoxName") as RadTextBox).Text = editedItem["Name2"].Text; 

                //DKPI.Visible = true;
                
                ////(userControl.FindControl("Name") as RadTextBox).Text = tlda[editedItem.DisplayIndex]["Name"].ToString();
                ////string dataKeyValue = editedItem.ParentItem.GetDataKeyValue("EmployeeID").ToString();

                //ShowProgress(editedItem["ID"].Text);
            }

        }

        private void ShowKPI(TreeListDataItem editedItem)
        {
            (DKPI.FindControl("TextBoxName") as RadTextBox).Text = editedItem["Name2"].Text;
            //(DKPI.FindControl("RadNumericTextBoxWeight") as RadNumericTextBox).Value = Convert.ToInt32(editedItem["Weight"].Text);
            DKPI.Visible = true;

            ShowKPIProgress(editedItem["ID"].Text);
        }

        private void ShowPerspective(TreeListDataItem editedItem)
        {
            (DKPI.FindControl("TextBoxName") as RadTextBox).Text = editedItem["Name2"].Text;
            //(DKPI.FindControl("RadNumericTextBoxWeight") as RadNumericTextBox).Value = Convert.ToInt32(editedItem["Weight"].Text);
            //DPerspective.Visible = true;

            ShowPerspectiveProgress(editedItem["ID"].Text);
        }

        
        private void ShowBSC()
        {
            throw new NotImplementedException();
        }


        private void ShowKPIProgress(string p)
        {
            BSCEntities context = new BSCEntities();

            int kpi_id = Convert.ToInt32(p);

            var data = (from kp in context.KPI_Progress
                       where kp.KPI_FK == kpi_id
                       orderby kp.Date
                       select new { kp.Date, kp.Current_Value, kp.Start_Value, kp.Target_Value }).ToList();

            RadChart1.Series.RemoveSeries();

            RadChart1.DataSource = data;
            RadChart1.DataBind();
        }

        private void ShowPerspectiveProgress(string p)
        {
            BSCEntities context = new BSCEntities();

            int perspective_id = Convert.ToInt32(p);

            var data = (from k in context.KPIs
                       where k.Perspective_FK == perspective_id
                       from kp in context.KPI_Progress
                       where kp.KPI_FK == k.KPI_ID
                      // group kp by kp.da
                       orderby kp.Date
                       select kp).ToList();

            //Hashtable ht = CalculatePerspectiveProgress(data);


            Dictionary<DateTime, int> weights = new Dictionary<DateTime,int>();
            Dictionary<DateTime, double> progress = new Dictionary<DateTime,double>();
            Hashtable progress2 = new Hashtable();
            foreach (var d in data)
            {
                if (!weights.ContainsKey(d.Date))
                {
                    weights[d.Date] = d.Weight;
                    //progress[d.Date] = d.Weight * d.Progress;
                    progress2[d.Date] = d.Weight * d.Progress;
                }
                else
                {
                    weights[d.Date] += d.Weight;
                    //progress[d.Date] += d.Weight * d.Progress;
                    progress2[d.Date] = (double)progress2[d.Date] + d.Weight * d.Progress;
                }
            }

            Hashtable progressdivided = new Hashtable();
            foreach(var pr in progress2)
            {
                string s = pr.ToString();
                 //= pr.Value / weights[pr.Key];
                //DictionaryEntry de = new DictionaryEntry();
                //de["asd"] = (float)((DictionaryEntry)pr).Value / weights[(DateTime)((DictionaryEntry)pr).Key];
                //((DictionaryEntry)pr).Value = (float)((DictionaryEntry)pr).Value / weights[(DateTime)((DictionaryEntry)pr).Key];

                progressdivided[((DictionaryEntry)pr).Key] = Convert.ToDouble(((DictionaryEntry)pr).Value) / (int)(weights[Convert.ToDateTime(((DictionaryEntry)pr).Key.ToString())]);
            }


            //data[0].Date;
            RadChart1.Series.RemoveSeries();
            RadChart1.DataSource = progressdivided;
            RadChart1.DataBind();
            
        }

        //private Hashtable CalculatePerspectiveProgress(object data)
        //{
            
        //}

    }
}